package com.wzx.user.business.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzx.common.exception.LeadNewsException;
import com.wzx.common.pojo.resp.Result;
import com.wzx.user.common.RedisPwdErrorNumCommon;
import com.wzx.user.pojo.shop.dto.ReleaseDynamicDto;
import com.wzx.user.pojo.shop.pojo.ReleaseDynamic;
import com.wzx.user.pojo.shop.vo.PlaceAnOrderVo;
import com.wzx.user.pojo.shop.vo.QueryReleaseByPage;
import com.wzx.user.pojo.shop.vo.ReleaseDynamicVo;
import com.wzx.user.business.shop.mapper.ReleaseDynamicMapper;
import com.wzx.user.business.shop.service.ReleaseDynamicService;
import com.wzx.user.mapper.NotesMapper;
import com.wzx.user.mapper.WalletMapper;
import com.wzx.user.pojo.Notes;
import com.wzx.user.pojo.Wallet;
import com.wzx.user.service.CommonService;
import com.wzx.user.utils.AmountUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/2/16 - 19:10
 * @description 标题
 */
@Slf4j
@Service
public class ReleaseDynamicServiceImpl extends ServiceImpl<ReleaseDynamicMapper, ReleaseDynamic> implements ReleaseDynamicService {

    @Autowired
    private ReleaseDynamicMapper releaseDynamicMapper;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private RedisPwdErrorNumCommon redisPwdErrorNumCommon;

    @Override
    public Result queryByTypePage(QueryReleaseByPage queryReleaseByPage) {
        Page<ReleaseDynamic> pages = new Page<>(queryReleaseByPage.getPage(), queryReleaseByPage.getSize());
        Page<ReleaseDynamic> resultPage = releaseDynamicMapper.queryByTypePage(queryReleaseByPage.getTypeId(),
                queryReleaseByPage.getState(),
                queryReleaseByPage.getReleaseUserId(),
                queryReleaseByPage.getIsReleaseUser(),
                pages);
        return Result.successByPage(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal(), resultPage.getPages(), resultPage.getRecords());
    }

    @Override
    public List<ReleaseDynamicDto> queryByOrder(QueryReleaseByPage queryReleaseByPage) {
        return releaseDynamicMapper.queryByOrder(queryReleaseByPage);
    }

    @Override
    public void placeAnOrder(PlaceAnOrderVo placeAnOrderVo) throws LeadNewsException {
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(placeAnOrderVo.getReleaseDynamicId());
        if (releaseDynamic == null) {
            throw new LeadNewsException("未找到该商品！");
        }

        if (!releaseDynamic.getState().equals("1") || releaseDynamic.getOrderState().equals("2")) {
            throw new LeadNewsException("订单已被处理！");
        }
        releaseDynamic.setState(placeAnOrderVo.getState());
        releaseDynamic.setOrderUserId(placeAnOrderVo.getOrderUserId());
        releaseDynamic.setOrderState(placeAnOrderVo.getOrderState());
        releaseDynamicMapper.updateById(releaseDynamic);
    }

    @Override
    public void cancelOrder(Integer releaseDynamicId) throws LeadNewsException {
        //查询发布表
        //（1：发布中；
        //  2：用户下单；3：商家已发货；4：商家已送达；5：用户已完成签收；
        //  6：用户已接单；7：用户开始处理订单；8：用户已完成订单；9：商户已完成签收；
        //  10：订单完成。
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(releaseDynamicId);
        //全国代办
        if (releaseDynamic.getDynamicType().equals("1") && Integer.parseInt(releaseDynamic.getState()) >= 3) {
            throw new LeadNewsException("商家已发货，请联系商家取消订单！");
        }

        if (releaseDynamic.getDynamicType().equals("2") && (releaseDynamic.getState().equals("9") || releaseDynamic.getState().equals("10"))) {
            throw new LeadNewsException("订单已完成，无法取消订单！");
        }

        //更改发布状态
        releaseDynamic.setOrderState("1");
        releaseDynamic.setState("1");
        releaseDynamic.setOrderUserId(0);
        releaseDynamicMapper.updateById(releaseDynamic);
    }

    @Override
    public void changeState(PlaceAnOrderVo placeAnOrderVo) throws LeadNewsException {
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(placeAnOrderVo.getReleaseDynamicId());

        //当前状态小于更改状态不能改变
        if (Integer.parseInt(releaseDynamic.getState()) >= Integer.parseInt(placeAnOrderVo.getState())) {
            throw new LeadNewsException("状态无法回退！");
        }

        //更新状态
        releaseDynamic.setState(placeAnOrderVo.getState());
        if (releaseDynamic.getState().equals("10")) {
            //订单已完成
            releaseDynamic.setOrderState("3");
        }
        releaseDynamicMapper.updateById(releaseDynamic);
    }

    @Override
    public void removeOrderByOrderId(Integer releaseDynamicId) {
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(releaseDynamicId);
        releaseDynamic.setOrderDataState("2");
        releaseDynamicMapper.updateById(releaseDynamic);
    }

    @Override
    public void removeOrderByReleaseUserId(Integer releaseDynamicId) {
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(releaseDynamicId);
        releaseDynamic.setReleaseUserDataState("2");
        releaseDynamicMapper.updateById(releaseDynamic);
    }

    @Override
    public ReleaseDynamicDto selectById(Integer releaseDynamicId) {
        return releaseDynamicMapper.queryByID(releaseDynamicId);
    }

    @Override
    public void createPublicationByZfb(ReleaseDynamicVo releaseDynamicVo) {
        //1，将发布信息添加到数据库中
        ReleaseDynamic releaseDynamic = new ReleaseDynamic();
        BeanUtils.copyProperties(releaseDynamicVo, releaseDynamic);
        releaseDynamic.setPrice(AmountUtils.handlerAmountByInteger(releaseDynamicVo.getPrice()));
        releaseDynamicMapper.insert(releaseDynamic);

        //2，账单信息添加进入账单数据库
        //添加历史数据
        Notes notes = new Notes();
        notes.setType("支付宝:发布代办");
        notes.setPrice(AmountUtils.handlerAmountByInteger(releaseDynamicVo.getPrice()));
        notes.setUserId(releaseDynamicVo.getReleaseUserId());
        notes.setState("0");
        notes.setMethod("3");
        notesMapper.insert(notes);
    }

    @Override
    public void createPublicationByAmount(ReleaseDynamicVo releaseDynamicVo) throws LeadNewsException {
        redisPwdErrorNumCommon.getPwdErrorNum(releaseDynamicVo.getReleaseUserId(),1);

        //1，判断支付密码是否正确
        QueryWrapper<Wallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", releaseDynamicVo.getReleaseUserId());
        Wallet wallet = walletMapper.selectOne(queryWrapper);

        if (wallet == null) {
            log.error("用户：{}，输入密码是：{}", releaseDynamicVo.getReleaseUserId(), releaseDynamicVo.getPwd());
            throw new LeadNewsException("未设置支付密码！");
        }
        boolean decrypt = commonService.decrypt(releaseDynamicVo.getReleaseUserId(), releaseDynamicVo.getPwd(), wallet.getPassword());
        if (!decrypt) {
            log.error("用户：{}，输入密码是：{}", releaseDynamicVo.getReleaseUserId(), releaseDynamicVo.getPwd());
            redisPwdErrorNumCommon.setPwdErrorNum(releaseDynamicVo.getReleaseUserId(),1);
            throw new LeadNewsException("密码输入错误！");
        }
        redisPwdErrorNumCommon.closePwdErrorNum(releaseDynamicVo.getReleaseUserId(),1);

        //2，修改用户余额
        wallet.setBalance(wallet.getBalance() - AmountUtils.handlerAmountByInteger(releaseDynamicVo.getPrice()));
        walletMapper.updateById(wallet);

        //3，添加发布信息
        ReleaseDynamic releaseDynamic = new ReleaseDynamic();
        BeanUtils.copyProperties(releaseDynamicVo, releaseDynamic);
        releaseDynamic.setPrice(AmountUtils.handlerAmountByInteger(releaseDynamicVo.getPrice()));
        releaseDynamicMapper.insert(releaseDynamic);

        //4，添加历史信息
        Notes notes = new Notes();
        notes.setType("余额支付:发布代办");
        notes.setPrice(AmountUtils.handlerAmountByInteger(releaseDynamicVo.getPrice()));
        notes.setUserId(releaseDynamicVo.getReleaseUserId());
        notes.setState("0");
        notes.setMethod("3");
        notesMapper.insert(notes);

    }

    @Override
    public void placeAnOrderByAmount(PlaceAnOrderVo placeAnOrderVo) throws LeadNewsException {
        redisPwdErrorNumCommon.getPwdErrorNum(placeAnOrderVo.getOrderUserId(),1);

        //1，判断支付密码是否正确
        QueryWrapper<Wallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", placeAnOrderVo.getOrderUserId());
        List<Wallet> wallets = walletMapper.selectList(queryWrapper);
        if (wallets == null) {
            log.error("用户：{}未设置支付密码", placeAnOrderVo.getOrderUserId());
            throw new LeadNewsException("未设置支付密码！");
        }
        boolean decrypt = commonService.decrypt(placeAnOrderVo.getOrderUserId(), placeAnOrderVo.getPwd(), wallets.get(0).getPassword());
        if (!decrypt) {
            log.error("用户：{}，输入密码是：{}", placeAnOrderVo.getOrderUserId(), placeAnOrderVo.getPwd());
            redisPwdErrorNumCommon.setPwdErrorNum(placeAnOrderVo.getOrderUserId(),2);
            throw new LeadNewsException("密码输入错误！");
        }
        redisPwdErrorNumCommon.closePwdErrorNum(placeAnOrderVo.getOrderUserId(),1);

        //2，查询订单信息
        ReleaseDynamic releaseDynamic = releaseDynamicMapper.selectById(placeAnOrderVo.getReleaseDynamicId());
        if (releaseDynamic == null) {
            throw new LeadNewsException("未找到该商品！");
        }

        if (!releaseDynamic.getState().equals("1") || releaseDynamic.getOrderState().equals("2")) {
            throw new LeadNewsException("订单已被处理！");
        }

        releaseDynamic.setState(placeAnOrderVo.getState());
        releaseDynamic.setOrderUserId(placeAnOrderVo.getOrderUserId());
        releaseDynamic.setOrderState(placeAnOrderVo.getOrderState());
        releaseDynamicMapper.updateById(releaseDynamic);

        //3，修改用户余额
        wallets.get(0).setBalance(wallets.get(0).getBalance() - releaseDynamic.getPrice());
        walletMapper.updateById(wallets.get(0));

        //4，添加购买记录
        Notes notes = new Notes();
        notes.setType("余额支付:闲置下单");
        notes.setPrice(releaseDynamic.getPrice());
        notes.setUserId(placeAnOrderVo.getOrderUserId());
        notes.setState("0");
        notes.setMethod("3");
        notesMapper.insert(notes);
    }
}
